package com.wuhuiyue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuhuiyue.entity.User;
import com.wuhuiyue.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @author hy woo
 * @date 2022/6/11 9:51
 */
@Service("UserDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",s);
        User user = userMapper.selectOne(wrapper);
        if (user==null){
            throw new UsernameNotFoundException("用户"+s+"不存在");
        }
        // 创建权限
        Set<SimpleGrantedAuthority> authorities=new HashSet<>();
        // 授权
        authorities.add(new SimpleGrantedAuthority(user.getRole()));
        user.setAuthorities(authorities);
        return user;
    }
}
